<script setup>
import _ from 'lodash'
import {ref, reactive, computed, watch, onMounted, toRefs} from 'vue';
import {
  getAnimePlain,
  getLowPlain,
  getNodeCompDefInfo,
  getRespPlain,
  getUniqNewPropName,
  isDataNode,
  isMicroComp
} from '../utils/mutil';
import BuilderPropStyle from "./builder-prop-style.vue";
import NodeDataPicker from './ele/node-data-picker.vue';
import BuilderVars from "./builder-vars.vue";
// import cNavProp from './ele/nav/prop.vue';
// import cChartProp from './ele/charts/prop.vue';
import cDataPageSub from './ele/data-page-sub.vue';
// import cSetting from './ele/setting.vue';
// import BuilderNodePropext from './builder-node-propext.vue'; //TODO
import NodeFormulaRender from "./ele/node-formula-render.vue";
import BuilderNodesAdd from "./builder-nodes-add.vue";
import BuilderNodePropext from './builder-node-propext.vue'
// import BuilderNodesAddTools from "./builder-nodes-add-tools";
import {DFT_ICONS} from "@jzl/icons";
import {$pageUtils} from "@jzl/utils";
// import PageItemCommonStyle from "@jzl/utils/common/pi-common-style.js";
import BuilderNodesLowcode from "./builder-nodes-lowcode.vue";

// 定义props
const props = defineProps({
  isEditItem: {
    type: Boolean,
    default: false
  },
  currentItemElCode: String,
  hoverItemElCode: String,
  currentIndex: {
    type: Number,
    default: -1
  },
  elemNodes: {
    type: [Array, Object],
    default: []
  },
  currentItem: {
    type: Object
  },
  currentNode: {
    type: Object,
    default: {}
  },
  currentItems: Array,
  currentPage: {
    type: Object
  },
  items: {
    type: Array
  },
  propTab: {
    type: String,
    default: 'style'
  },
  popData: Object,
  lowcode: Object
});

// 定义emits
const emit = defineEmits([ 'tabChange', /*'changeElemNodes', 'selectItem'*/ ]);

// 使用defineExpose暴露方法给父组件
defineExpose({
  // 这里可以列出需要暴露的方法
});

// 状态
const state = reactive({
  compEleData: null,  // 当前元素最近的微组件节点数据
  compNode: null,     // 当前元素最近的微组件节点
  currentEleData: {},
  // currentNode: {},
  styleTab: props.propTab || 'style',
  styleCommon: {},
  styleHover: {},
  // pageStyle: {},
  // timer: null,
  // handlers: {},
  pageSettingShow: false,
  pageSettingWinName: '',
  pageSettingStepActive: '2',
  tplCate: {} // 假设tplCate需要初始化为空对象
});

const {
  compEleData,
  compNode,

  currentEleData,
  // currentNode,
  styleTab,
  styleCommon,
  styleHover,
  // pageStyle,
  // timer,
  // handlers,
  pageSettingShow,
  pageSettingWinName,
  // pageSettingStepActive,
} = toRefs(state)

const isDataEnable = computed(() => {
  return _.get(props.currentNode, 'def') ? isDataNode(_.get(props.currentNode, 'def')) : false;
});

/*const isLeafNode = computed(() => {
  let nodeType = _.get(state.currentNode, "def._type") || _.get(state.currentNode, "def._node") || _.get(state.currentNode, "def._component");
  return _.indexOf(['text', 'icon', 'img', 'video'], nodeType) >= 0;
});*/

// 方法实现
/*const isComp = (name) => {
  return props.currentItem && props.currentItem.component === name;
};*/

const getClosestCompNode = (elCode) => {
  let nodePaths = $utils.getTreePath(elCode, props.elemNodes, "code", 'children', true);

  if(nodePaths?.length) {
    for(let i = nodePaths.length - 1; i >= 0; i--) {
      let nodeInfo = nodePaths[i];
      if(isMicroComp(nodeInfo?.def)) return nodeInfo;
    }
  }
  return null;
};

const initElemCurrentNode = () => {
  // let node = this.$refs.nodesTree.getNode(this.currentItemElCode);
  // let nodeData = $utils.getTreeData(props.elemNodes, "code", props.currentItemElCode);

  let closestCompNode = getClosestCompNode(props.currentItemElCode)
  let closestCompEleData = closestCompNode?.def;

  compNode.value = closestCompNode;
  compEleData.value = closestCompEleData;

  let currentEleData = props.currentNode?.def;
  state.currentEleData = currentEleData || {};
  // state.currentNode = nodeData;

  if (!state.currentEleData._ss) {
    // this.$set(this.currentEleData, "_ss", {});
    state.currentEleData._ss = {};
  }

  if (!state.currentEleData._sh) {
    // this.$set(this.currentEleData, "_sh", {});
    state.currentEleData._sh = {};
  }

  if (!state.currentEleData._evts) {
    // this.$set(this.currentEleData, "_evts", []);
    state.currentEleData._evts = []
  }

  // if(!this.currentEleData._low) {
  let _low = state.currentEleData._low;
  let _lowInfo = _.defaultsDeep(_low || {}, getLowPlain());

  state.currentEleData._low = _lowInfo;
  // this.$set(this.currentEleData, "_low", _lowInfo);
  // }

  // if(!this.currentEleData._resp) {
  let _resp = state.currentEleData._resp;
  let _respInfo = _.defaultsDeep(_resp || {}, getRespPlain());

  state.currentEleData._resp = _respInfo;
  // this.$set(this.currentEleData, "_resp", _respInfo);
  // }

  // if(!this.currentEleData._anime) {
  let _anime = state.currentEleData._anime;
  let _animeInfo = _.defaultsDeep(_anime || {}, getAnimePlain());

  state.currentEleData._anime = _animeInfo;
  // this.$set(this.currentEleData, "_anime", _animeInfo);

  if (!state.currentEleData._sticky) {
    state.currentEleData._sticky = {};
    // this.$set(this.currentEleData, "_sticky", {});
  }
  // }*/

  let styleMix = $pageUtils.getInitMixStyle(_.cloneDeep(state.currentEleData));

  state.styleCommon = _.get(styleMix, "_ss");
  state.styleHover = _.get(styleMix, "_sh");
};

// const initHandlers = () => {
//   state.handlers = $jutils.Page.getHandlersByForm(props.currentPage);
// };

const handleLowcodeChange = (lowcode) => {
  // $bus.$emit("global:lowcodeChange", lowcode);
};

const handleClearStyle = () => {
  if(state.styleTab === 'hover') {
    if(state.currentEleData._sh) state.currentEleData._sh = {}
  } else {
    if(state.currentEleData._ss) state.currentEleData._ss = {}
  }
}

// 生命周期钩子
onMounted(() => {
  // initHandlers();
});

// 保持拖拽改变多大小时，实时改变
watch(() => [ state?.currentEleData._ss?.width, state?.currentEleData._ss?.height ], (val, oldVal) => {
  // console.log('---------------watch styleCommon ....', JSON.stringify(val), JSON.stringify(oldVal))
  state.styleCommon.width = state?.currentEleData._ss?.width;
  state.styleCommon.height = state?.currentEleData._ss?.height;
})

watch(() => [ state?.currentEleData._ss?.left, state?.currentEleData._ss?.top ], (val, oldVal) => {
  // console.log('---------------watch styleCommon ....', JSON.stringify(val), JSON.stringify(oldVal))
  state.styleCommon.left = state?.currentEleData._ss?.left;
  state.styleCommon.top = state?.currentEleData._ss?.top;
})

watch(
  () => props.currentNode?.code,
  (code) => {
    initElemCurrentNode();
  },
  { deep: true }
);

watch(
  () => state.styleCommon,
  (val) => {
    if (state.currentEleData) {
      state.currentEleData._ss = $pageUtils.clearDefaultStyleUnit(val);
    }
  },
  {deep: true}
);

watch(
  () => state.styleHover,
  (val) => {
    if (state.currentEleData) {
      state.currentEleData._sh = $pageUtils.clearDefaultStyleUnit(val);
    }
  },
  {deep: true}
);

watch(
  () => props.propTab,
  (val) => {
    state.styleTab = val;
  }
);

watch(
  () => state.styleTab,
  (val) => {
    emit("tabChange", val);
  }
);

/*watch(
  () => props.currentPage?.page_code,
  (val) => {
    initHandlers();
  }
);*/
</script>

<template>
  <div class="ele-design-prop" :class="{ 'disabled': !isEditItem }">
    <div class="ele-design-prop-wrap">
      <template v-if="styleTab === 'style' || styleTab === 'hover'">
        <div class="elem-node-header1">
          <el-tabs v-model="styleTab">
            <el-tab-pane label="元素样式" name="style">
              <template #label>
              <span class="flex items-center">
                <JIcon icon="ri:palette-line" class="div mr-1" />元素样式
              </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="悬浮样式" name="hover">
              <template #label>
              <span class="flex items-center">
                <JIcon icon="ri:palette-fill" class="div mr-1" />悬浮样式
              </span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div
          v-if="currentEleData"
          class="flex-1 overflow-y-auto"
        >
          <BuilderPropStyle
            v-model="styleCommon"
            v-show="styleTab === 'style'"
            class="border-t-0"
            :current-item-el-code="currentItemElCode"
            :hover-item-el-code="hoverItemElCode"
            :current-ele-data="currentEleData"
            :current-node="currentNode"
          />
          <BuilderPropStyle
            v-model="styleHover"
            v-show="styleTab === 'hover'"
            class="border-t-0"
            :current-item-el-code="currentItemElCode"
            :hover-item-el-code="hoverItemElCode"
            :current-ele-data="currentEleData"
            :current-node="currentNode"
          />
        </div>
        <div
          v-if="currentEleData"
          class="p-[10px] text-center flex justify-around"
        >
          <el-switch
            v-model="currentEleData._rh"
            active-text="hover块"
            v-tippy content="子元素都按悬浮样式显示"
          />
          <el-button
            type="text"
            @click="handleClearStyle"
            v-tippy content="清除当前自定义样式"
          >清除样式</el-button>
        </div>
      </template>

      <template v-if="styleTab === 'item' || styleTab === 'comp'">
        <c-data-page-sub
          v-if="currentItem?.component === 'jzlPageSub'"
          :item="currentItem"
          :pages="pages"
          :current-page-items="items"
        />
        <BuilderVars
          v-else-if="currentItem"
          v-model="currentItem.vars"
          :dialog="true"
          :is-item="true"
          trigger-page-type="pageItem"
          :item="currentItem"
          :page="currentPage"
          label="模块变量"
          v-bind="$attrs"
        />
<!--      </template>
      <template v-else-if="styleTab === 'item' || styleTab === 'comp'">-->
        <template v-if="compEleData">
<!--          <hr class="ele-prop-line"/>-->
          <div class="elem-design-prop-logic p-0">
            <h5 class="wd-vars-header" style="margin-bottom: 0px;">组件设置【{{ compNode?.name }}】</h5>
            <el-form
              v-if="compEleData._mo"
              class="elem-design-prop-logic ele-design-comp-vars"
              label-position="top"
            >
              <el-form-item
                v-for="(mo, prop) in compEleData._mo"
              >
                <template #label>
                  <h5 style="margin-bottom: 0px;">{{ mo.label || prop }}</h5>
                </template>
                <NodeDataPicker
                  v-model="mo.var"
                  v-bind="$attrs"
                  :item="currentItem"
                  :page="currentPage"
                  :current-ele-data="currentEleData"
                  :current-node="currentNode"
                  :elem-nodes="elemNodes"
                />
              </el-form-item>
            </el-form>
            <BuilderNodePropext
              v-bind="$attrs"
              :ele-def="compEleData"
              :item="currentItem"
              :page="currentPage"
              :current-ele-data="compEleData"
              :current-node="compNode"
              :elem-nodes="elemNodes"
            />
          </div>
        </template>
      </template>
      <div
        v-else-if="styleTab === 'data'"
        class="flex-1 overflow-y-auto"
      >
        <template v-if="currentEleData">
          <el-form class="elem-design-prop-logic" label-position="top">
            <el-form-item label="数据绑定">
              <template #label>
                <h5 class="mt-[-3px]">数据绑定</h5>
              </template>
              <NodeDataPicker
                v-model="currentEleData._value"
                v-bind="$attrs"
                :item="currentItem"
                :page="currentPage"
                :current-ele-data="currentEleData"
                :current-node="currentNode"
                :elem-nodes="elemNodes"
                :disabled="!isDataEnable"
              />
            </el-form-item>
            <el-form-item label="渲染公式">
              <template #label>
                <h5>数据渲染公式</h5>
              </template>
              <NodeFormulaRender
                v-model="currentEleData._formula"
                v-bind="$attrs"
                :item="currentItem"
                :page="currentPage"
                :current-ele-data="currentEleData"
                :current-node="currentNode"
                :elem-nodes="elemNodes"
                :disabled="!isDataEnable"
              />
            </el-form-item>
          </el-form>
          <!--                </template>
                          <template v-if="styleTab === 'event'">-->
          <BuilderNodesLowcode
            :current-ele-data="currentEleData"
            :page="currentPage"
            :current-page="currentPage"
            :lowcode="lowcode"
            v-bind="$attrs"
          />

          <hr class="ele-prop-line"/>
          <div class="elem-design-prop-logic">
            <h5><span>事件</span></h5>
            <EventTags
              v-model="currentEleData._evts"
              :page="currentPage"
              :page-item-code="currentItem?.page_item_code"
              :support="currentEleData._se"
              :lowcode="lowcode"
            />
          </div>
        </template>
        <!--<data-node-value v-show="styleTab === 'data'" v-bind="$attrs" :item="currentItem" :page="currentPage"
                         :current-ele-data="currentEleData" :current-node="currentNode" :elem-nodes="elemNodes"
                         :class="{ 'disabled': !isDataEnable }"></data-node-value>-->
      </div>
      <template v-else-if="styleTab === 'node'">
        <BuilderNodesAdd
          :current-item="currentItem"
          :current-items="currentItems"
          :pop-data="popData"
          :current-node="currentNode"
          v-bind="$attrs"
        />
      </template>
    </div>

    <el-dialog
      :title="pageSettingWinName"
      v-model="pageSettingShow"
      :fullscreen="true"
      custom-class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true">
      <PageSetting
        v-if="pageSettingShow"
        :show.sync="pageSettingShow"
        :page-id="currentPage?.page_id"
        :is-view="false"
        @close.stop="pageSettingShow = false"
        @lowcode-change="handleLowcodeChange"
      />
    </el-dialog>
    <!--</div>-->
  </div>
</template>

<style lang="scss" scoped>
hr.ele-prop-line {
  margin: 5px 0px;
  color: var(--j-fill-color-dark);
}

.ele-design-prop-wrap {
  display: flex;
  flex-flow: column;
  width: 330px;
  overflow-y: auto;

  ::v-deep .el-tabs__item {
    font-size: 12px;
    padding: 0px 15px;
    color: var(--j-text-color-secondary);
    font-weight: bold;
    transition: all .2s;

    &.is-active, &:hover {
      color: var(--j-text-color-primary);
    }
  }
  &.disabled-node-create {
    &:before {
      content: "叶子节点下不能添加子节点";
      position: absolute;
      left: 0px;
      top: 0px;
      right: 0px;
      bottom: 0px;
      background: rgba(0, 0, 0, .5);
      z-index: 10;
      color: #FFF;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 15px;
      font-weight: bold;
      letter-spacing: 2px;
    }
  }
}

.ele-design-comp-vars {
  background: var(--j-fill-color-light);
  border-bottom: 1px solid var(--j-border-color-light);
  padding-bottom: 10px;
  margin-bottom: 10px;
}

</style>
